<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 致承
 -->

<template>
  <div>
    <van-form class="zhi-cheng">
      <!-- 账号 -->
      <van-field
        v-model="ruleForm.userName"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <!-- 密码 -->
      <van-field
        v-model="ruleForm.passWord"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <!-- 任务类型 -->
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-radio-group v-model="type" direction="horizontal">
            <van-radio
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.type"
              checked-color="#e4393c"
            >{{ option.label }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <!-- 提示 -->
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <!-- 按钮 -->
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>

    <!-- 选择账号 -->
    <van-dialog v-model="show" title="选择账号" :showConfirmButton="false" :showCancelButton="false">
      <van-cell v-for="(bind, index) in accountList" :key="index" center :title="bind.Account">
        <template #right-icon>
          <van-switch
            v-model="bind.status"
            active-color="#e4393c"
            size="24"
            @change="onChange(bind)"
          />
        </template>
      </van-cell>
    </van-dialog>
  </div>
</template>

<script>
import * as cheng from "@/api/zhi-cheng";
import { alertMsg, saveInfo, audio } from "@/utils/index";
export default {
  name: "ZhiCheng",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      // 参数
      ruleForm: {
        userName: "",
        passWord: "",
        mobile: "",
        picCode: "",
        smsCode: "",
        loginType: 1,
        roleType: 1
      },
      // 循环时间
      IntervalTime: 8,
      // 任务类型
      type: "0",
      typeOptions: [
        { label: "全部", type: "0" },
        { label: "淘宝、天猫", type: "1" },
        { label: "京东", type: "2" },
        { label: "拼多多", type: "3" }
      ],
      // 开始登陆 标记
      startFlag: false,
      // 定时器
      timer: null,
      // 任务ID
      taskId: "",
      // 接口返回提示
      returnContent: [],
      // 已有平台
      iconItems: [],
      activeIndex: "",
      accountList: [],
      show: false,
      // 已接单标记
      isAcceptSuc: false
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 27 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    returnContent() {
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 27 && this.index !== "") {
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.userName = this.item.user;
        this.ruleForm.passWord = this.item.pass;
        this.type = this.item.type || "0";

        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,
            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 27 && this.index !== "") {
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.userName = this.item.user;
      this.ruleForm.passWord = this.item.pass;
      this.type = this.item.pass || "0";
    }
  },
  methods: {
    // 开始接单
    onStart() {
      this.onLogin();
    },
    // 登录
    onLogin() {
      const _this = this;
      if (!this.startFlag) {
        this.returnContent = [];
        this.startFlag = true;
        // 登录提示
        this.returnContent.unshift(alertMsg("正在登录"));
        // 异步登录
        let param = {
          type: "post",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "X-Requested-With": "XMLHttpRequest"
          },
          data: this.ruleForm
        };
        cheng.ajaxFun(cheng.getLogin, param, res => {
          _this.returnContent.unshift(alertMsg(res.msg));
          if (res.code === 0) {
            // 登录成功  => 保存账号信息
            saveInfo({
              user: _this.ruleForm.userName,
              pass: _this.ruleForm.passWord,
              type: _this.type,
              index: _this.index
            });
            // 选择平台
            cheng.ajaxFun(cheng.getCookie, param, () => {
              _this.onGetBuyList(_this);
            });
          } else {
            _this.startFlag = false;
          }
        });
      } else {
        _this.onCancelTask(_this);
      }
    },
    // 获取平台账号
    onGetBuyList(_this) {
      let param = {
        type: "get",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          "X-Requested-With": "XMLHttpRequest"
        },
        data: {
          plat: _this.type
        }
      };
      cheng.ajaxFun(cheng.getBuyList, param, res => {
        let message = res.list.length === 0 ? "请先绑定买号" : res.msg;
        _this.returnContent.unshift(alertMsg(message));
        if (res.list.length !== 0) {
          _this.accountList = res.list;
          if (_this.accountList.length === 1) {
            _this.buyerId = _this.accountList[0].Id;
            _this.onChange(_this.accountList[0]);
          } else {
            _this.show = !_this.show;
          }
        }
      });
    },
    // 选择账号
    onChange(data) {
      const _this = this;
      _this.show = false;
      _this.returnContent.unshift(
        alertMsg("接单号: " + data.Account + "即将开始接单，请等待...")
      );
      _this.buyerId = data.Id;
      _this.onAcceptTask(_this);
    },
    // 接单
    onAcceptTask(_this) {
      clearInterval(_this.timer);
      let param = {
        type: "post",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          "X-Requested-With": "XMLHttpRequest"
        },
        data: {
          isMobile: 1,
          platformId: _this.type,
          buyerId: _this.buyerId,
          minPrice: 0,
          maxPrice: 9999
        }
      };
      cheng.ajaxFun(cheng.getOneKeyReceiptStart, param, res => {
        _this.returnContent.unshift(alertMsg(res.msg));
        if (res.code === 102) {
          _this.returnContent.unshift(alertMsg("接单成功"));
          _this.returnContent.unshift(alertMsg("做完任务后请手动点击开始接单"));
          audio();
          _this.isAcceptSuc = true;
          _this.startFlag = false;
          _this.$emit("changeOpened", {
            index: _this.activeIndex,
            status: "已接单",
            startFlag: false,
            content: ["接单成功，请前往做单..."]
          });
        } else {
          _this.timer = setInterval(() => {
            _this.onAcceptTask(_this);
          }, _this.IntervalTime * 1000);
        }
      });
    },
    // 取消派单
    onCancelTask(_this) {
      clearInterval(_this.timer);
      let param = {
        type: "post",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          "X-Requested-With": "XMLHttpRequest"
        },
        data: {
          isMobile: 1,
          platformId: _this.type,
          buyerId: _this.buyerId,
          minPrice: 0,
          maxPrice: 9999
        }
      };
      cheng.ajaxFun(cheng.getOneKeyReceiptStop, param, res => {
        _this.returnContent.unshift(alertMsg(res.msg));
        if (res.code != 0) {
          _this.timer = setInterval(() => {
            _this.onCancelTask(_this);
          }, _this.IntervalTime * 1000);
        } else {
          clearInterval(_this.timer);
          _this.isAcceptSuc = false;
          _this.startFlag = false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-open__form-code {
  width: 100%;
  @include flex($flexWrap: nowrap);
  .van-image {
    flex: 0 0 100px;
    height: 44px;
  }
}
</style>